<?php

namespace App\Services;
#按时间范围分表（处理"最新"查询）
class TimeBasedShardingService
{
    /**
     * 根据时间获取表后缀（按月分表）
     */
    public function getTableSuffixByTime($timestamp = null)
    {
        $timestamp = $timestamp ?: time();
        return date('Ym', $timestamp);
    }
    
    /**
     * 获取最近N个月的表名
     */
    public function getRecentTables($baseTable, $months = 12)
    {
        $tables = [];
        $current = time();
        
        for ($i = 0; $i < $months; $i++) {
            $time = strtotime("-$i months", $current);
            $suffix = $this->getTableSuffixByTime($time);
            $tables[] = "{$baseTable}_{$suffix}";
        }
        
        return $tables;
    }
    
    /**
     * 根据时间范围获取所有相关表
     */
    public function getTablesByTimeRange($baseTable, $startTime, $endTime)
    {
        $tables = [];
        $current = strtotime(date('Y-m-01', $startTime));
        $end = strtotime(date('Y-m-01', $endTime));
        
        while ($current <= $end) {
            $suffix = date('Ym', $current);
            $tables[] = "{$baseTable}_{$suffix}";
            $current = strtotime('+1 month', $current);
        }
        
        return $tables;
    }
}
